import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import Layout from "@/layout";

const imports = require("@/router/import_" + process.env.NODE_ENV);
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist
router.beforeEach(async (to, from, next) => {
  NProgress.start();
  document.title = getPageTitle(to.meta.title);
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.name;
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          await Promise.all([
            store.dispatch("user/getInfos"),
            store.dispatch("user/getrole"),
            store.dispatch("user/getInfomation"),
          ]);
          if (store.getters.menus.length === 0) {
            global.antRoute = [];
            next();
          }
          const menus = filterAsyncRouter(store.getters.menus);
          // 优化1: 移除冗余代码，使用统一的构造函数创建对象
          menus.forEach((e) => {
            if (e.children) {
              e.children.forEach((f) => {
                Object.assign(f, {
                  meta: {
                    icon: f.icon,
                    title: f.name,
                  },
                });
                f.name = "";
              });
            }
            Object.assign(e, {
              meta: {
                icon: e.icon,
                title: e.name,
              },
              alwaysShow: true,
              redirect: e.path,
            });
            e.name = "";
          }); 
          menus.push({
            path: "*",
            redirect: "/404",
          });
          router.addRoutes(menus);
          global.antRouter = menus;
          next({ ...to, replace: true });
        } catch (error) {
          await store.dispatch("user/resetToken");
          Message.error({ message: error || "出现错误，请稍后再试" });
          const encodedPath = encodeURIComponent(to.path); // 优化2: 对重定向路径进行编码
          next(`/login?redirect=${encodedPath}`);
          NProgress.done();
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${encodeURIComponent(to.path)}`); // 使用编码
      NProgress.done();
    }
  }
});

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter((route) => {
    if (route.component) {
      if (route.component === "Layout") {
        route.component = Layout;
      } else {
        route.component = imports(route.component); // 导入组件
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });

  return accessedRouters;
}
router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
